package com.eunion.web.cms.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eunion.common.util.CommUtils;
import com.eunion.core.ExcelUtil;
import com.eunion.core.LogUtil;
import com.eunion.core.common.DeleteVo;
import com.eunion.core.common.JsonVo;
import com.eunion.core.exception.ValidateException;
import com.eunion.fileserver.upload.FileInfo;
import com.eunion.web.cms.entity.University;
import com.eunion.web.cms.entity.UniversitySetMajor;
import com.eunion.web.cms.entity.spec.UniversitySetMajorSpec;
import com.eunion.web.cms.service.UniversitySetMajorService;
import com.eunion.web.common.base.BaseService;
import com.eunion.web.common.base.BaseTableCommonController;
import com.eunion.web.common.vo.Web;

/**
 * 学校开设的专业
 */
@Controller
@RequestMapping("/api/university-majors")
@PreAuthorize("hasAuthority('college:major')")
public class UniversitySetMajorResource extends BaseTableCommonController<UniversitySetMajor, Long> {

    @Override
    protected BaseService<UniversitySetMajor, Long> getBaseService() {
        return universitySetMajorService;
    }

    @Autowired
    private UniversitySetMajorService universitySetMajorService;
    
    /**
     * 进入学校专业管理页面
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return getUrlBase();
    }

    @Override
    protected String getUrlBase() {
        return "admin/universitymajor/universitymajor";
    }
    
    /**
     * 学校开设专业导入
     * @param obj
     * @param result
     * @param model
     * @param request
     * @return
     */
    @PreAuthorize("hasAuthority('college:major:import')")
    @PostMapping("/importData")
    public String importData(FileInfo obj, BindingResult result, Model model, HttpServletRequest request) {
        try {
            checkBindResult(result);
            if (StringUtils.isNotBlank(obj.getFilepath())) {
                String filepath = obj.getFilepath();
                String fileType = filepath.substring(filepath.lastIndexOf(".") + 1);
                InputStream in = null;

                Workbook wb = null;
                if (fileType.equals("xls")) {
                    in = new FileInputStream(filepath);
                    wb = new HSSFWorkbook(in);
                } else if (fileType.equals("xlsx")) {
                    in = new FileInputStream(filepath);
                    wb = new XSSFWorkbook(in);
                } else {
                    setModuleStatusError(model, "文件格式错误");
                    setModuleImport(model);
                    return getUrlBase().concat("-import");
                }

                // 开始解析数据
                Sheet sheet = wb.getSheetAt(0);
                List<UniversitySetMajor> list = ExcelUtil.readUniversityMajor(sheet);
                // 上传文件的原始名称
                String fileNameOrg = obj.getFileNameOrg();
                List<UniversitySetMajor> toSaveUniversitySetMajor = new ArrayList<>();
				List<UniversitySetMajor> toUpdateUniversitySetMajor = new ArrayList<>();
                if(universitySetMajorService.count() > 0) {
                	for(UniversitySetMajor major : list) {
                		List<UniversitySetMajor> findMajor = universitySetMajorService.findAll(UniversitySetMajorSpec.build(major,true));
                		if(CommUtils.isEmpty(findMajor)) {
                			toSaveUniversitySetMajor.add(major);
                		} else {
                			if(findMajor.size() == 1) {
                				major.setId(findMajor.get(0).getId());
                				toUpdateUniversitySetMajor.add(major);
                			} else {
                				universitySetMajorService.delete(findMajor);
                				toSaveUniversitySetMajor.add(major);
                			}
                		}
                	}	
                }
                for(UniversitySetMajor major : toUpdateUniversitySetMajor) {
                	universitySetMajorService.saveAndFlush(major);
                }
                List<UniversitySetMajor> resultList = getBaseService().save(toSaveUniversitySetMajor);
                if (CommUtils.isEmpty(toSaveUniversitySetMajor) && (null == resultList || resultList.size() < 1)) {
                    LogUtil.get(this.getClass()).error("save majorList failed");
                    setModuleStatusOK(model, "导入失败");
                } else {
                    setModuleStatusOK(model, "导入成功");
                }
            }
        } catch (ValidateException ve) {
            setModuleStatusError(model, ve.getMsg());
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("save obj error : {}", e);
            setModuleStatusError(model, "导入失败");
        }
        setModuleImport(model);
        return getUrlBase().concat("-import");
    }
    
    /**
     * 根据传入的数据ids,来删除对象.
     */
    @PostMapping(value = Web.URL_SEP_REMOVE)
    @ResponseBody
    protected JsonVo remove(@RequestBody DeleteVo<Long> dvo) {
        try {
            if (dvo != null && dvo.getIds() != null && dvo.getIds().size() > 0) {
                return super.remove(dvo);
            }
            return new JsonVo(true);
        } catch (Exception e) {
            LogUtil.get(this.getClass()).error("remove error ", e);
            return new JsonVo(false, "删除失败");
        }
    }
    
    @PostMapping(value = Web.URL_SEP_UPDATE)
    public String update(UniversitySetMajor major,BindingResult result, Model model, HttpServletRequest request) {
    	universitySetMajorService.saveAndFlush(major);
    	return getUrlBase();
    }
    
    @PostMapping(value = Web.URL_SEP_SAVE)
    public String save(UniversitySetMajor major,BindingResult result, Model model, HttpServletRequest request) {
    	universitySetMajorService.saveAndFlush(major);
    	return getUrlBase();
    }
}
